//
//  NetWorkTools.swift
//  我的微博
//
//  Created by gongjunna on 15/7/31.
//  Copyright © 2015年 itheima. All rights reserved.
//
/// 错误的类别标记
private let HMErrorDomainName = "com.itheima.error.network"

import UIKit
import AFNetworking

private enum NetWorkMethods  : String {
    
    case GET = "GET"
    case POST = "POST"

}
// 定义  枚举   返回值类型 Int
private enum NetWorkingError : Int {
    case emptyDataError = -1
    case emptyTokenError = -2
    
    //  用来 定义 -1 -2 具体的内容
    private var errorDescription : String {
        switch  self {
         
        case .emptyDataError : return "空数据"
        case .emptyTokenError : return "令牌为空"
        }
        
    }
    
    //  利用枚举  返回一个错误  里面有各种 说明
    private func error() -> NSError {
        return NSError(domain: HMErrorDomainName , code:rawValue , userInfo: [HMErrorDomainName : errorDescription])
    }
    

}
class NetWorkTools: AFHTTPSessionManager {
    // 检测  token 方法
    private func  checkToken(finished :MYCallBack) -> [String:AnyObject]? {
    
    let token = UserAccount.loadUserAccounts()
        if token == nil
        {
            finished(result: nil, error: NetWorkingError.emptyTokenError.error())
            return nil
        }
        
        return ["access_token": UserAccount.loadUserAccounts()!.access_token!]
    }
    
    // 获得  state
    func loadState(finished: MYCallBack) {
    
        guard  let pragma = checkToken(finished) else {
        
            return
        }
        let urlString = "2/statuses/home_timeline.json"
        request(NetWorkMethods.GET, urlstring: urlString, pargma: pragma, finised: finished)
    
    }
    
    
    
    
    
    
    
    private  let client_id = "3763573571"
    
    private let  appSecret = "d3e7a54be3676c0d067f252fa5d47c07"
   /// 外面要访问  不是私有
    let redirectUri = "http://www.baidu.com"
    
    static let shardNetWorkTool : NetWorkTools = {
        
        let urlString = "https://api.weibo.com/"
        
        let tools = NetWorkTools(baseURL: NSURL(string: urlString))
        
        // 设置  解析数据的格式
        tools.responseSerializer.acceptableContentTypes = NSSet(objects: "application/json", "text/json", "text/javascript", "text/plain") as Set<NSObject>
        return tools
        }()
    
    //  返回   授权界面  url
    func getAuthorize() -> NSURL {
        
        let urlString = "https://open.weibo.cn/oauth2/authorize?client_id=\(client_id)&redirect_uri=\(redirectUri)"
        
        return NSURL(string: urlString)!
    
    }
    
    typealias   MYCallBack = (result : [String : AnyObject]? ,error: NSError? ) -> ()
    func loginToken(code : String , finished:MYCallBack) {
        
        let urlString = "https://api.weibo.com/oauth2/access_token"

        let parma = ["client_id" :client_id ,"client_secret" :appSecret,"grant_type" :"authorization_code","code": code, "redirect_uri":redirectUri]
        
        request(NetWorkMethods.POST, urlstring: urlString, pargma: parma, finised: finished)
    }
    
    // TO DO  loadToken 封装
    // 加载用户信息
    func loadUserInfo(finished:MYCallBack) {
       
        let urlString = "2/users/show.json"
        let pargmas : [String : AnyObject] = ["access_token":UserAccount.loadUserAccounts()!.access_token! , "uid":UserAccount.loadUserAccounts()!.uid!]
       request(NetWorkMethods.GET, urlstring: urlString, pargma: pargmas, finised: finished)
        
    }
    
    // 封装 request 
    private func  request(methodss : NetWorkMethods , urlstring :String , pargma :AnyObject! ,finised :MYCallBack) {
        let successCallBack  : ((NSURLSessionDataTask!, AnyObject!) -> Void)! = { _ ,JSON in
            
            if  let result = JSON  as? [String:AnyObject] {
                
                finised(result: result, error: nil)
            } else  {
                finised(result: nil, error: NetWorkingError.emptyDataError.error())
                
            }
        }
        let failedCallBack : ((NSURLSessionDataTask!, NSError!) -> Void)!  =  { _ , error in
            
            finised(result: nil, error: error)
            
        }
        
        switch methodss {
        case NetWorkMethods.POST :
            POST(urlstring, parameters: pargma, success: successCallBack, failure: failedCallBack)
        case NetWorkMethods.GET :
            GET(urlstring, parameters: pargma, success: successCallBack, failure: failedCallBack)
            
        }
        
    }
    

}
